import axios from 'axios'
import qs from 'qs'
const service = axios.create({
    // baseURL: 'http://172.16.26.89:8877',
    timeout: 5000 // request timeout
})
// 请求头
service.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
/**
 * 设置响应拦截器
 */
service.interceptors.request.use(
    config => {
        if (process.env.NODE_ENV === 'production') {
            config.url = window.baseUrl + config.url; // 线上打包地址
        } else {
          config.url = 'http://49.233.23.77:8800' + config.url;// 开发环境
        }
        let token = localStorage.getItem('Authorization')
        if (token) {
            // 如果token不为null，否则传token给后台
            config.headers.Authorization = 'Bearer ' + token
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)
service.interceptors.response.use(
  response => {
      if (response.data.code === '401') {
          this.$message.warning('登录过期，请重新登录')
      }
    return response
  },
  error => {
    console.log(error)
  }
)


// 封装get方法
export function get(url, params, timeout) {
    return new Promise((resolve, reject) => {
        if (!params) {
            params = {
                timestamp: new Date().getTime()
            }
        } else {
            Object.assign(params, {
                timestamp: new Date().getTime()
            })
        }
        service.get(url, {
            params: params,
            paramsSerializer: params => {
                return qs.stringify(params, {indices: false})
            },
            timeout: timeout
        }
        , {
            headers: {
                'Content-Type': 'application/json',
                traditional: true
            },

        }
        ).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err);
            if (err.message.indexOf("timeout") > -1) {
                this.$message.info('请求超时');
            }
        })
    })
}

export function post(url, params, isJSON = false, headers = null) {
    let postParams = isJSON? JSON.stringify(params): qs.stringify(params);
    return new Promise((resolve, reject) => {
        service.post(url, postParams, {headers: headers || {
                'Content-Type': isJSON? 'application/json;charset=UTF-8': 'application/x-www-form-urlencoded;charset=UTF-8'
            }})
            .then(res => {
                resolve(res.data);
            })
            .catch(err =>{
                reject(err.data);
                if (err.message.indexOf("timeout") > -1) {
                  this.$message.info('请求超时');
                }
            })
    });
}

